package com.data.common.aliyun;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.data.common.exception.BootException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sunyk
 */
@Slf4j
public class AliyunUtilImpl implements AliyunFactorUtil {

    private AliyunFactorConfig config ;

    public AliyunUtilImpl(AliyunFactorConfig config) {
        this.config = config;
    }



    @Override
    public Map<String, Object> alyTwoElements(String name, String number) {
        String host = config.getTwo().getHost();
        String path = config.getTwo().getPath();
        String method = config.getTwo().getMethod();
        String appcode = config.getTwo().getAppcode();
        Map<String, Object> querys = new HashMap<String, Object>();
        querys.put("name", name);
        querys.put("number", number);
        Map<String,Object> map = new HashMap<>();
        try {
            cn.hutool.http.HttpResponse response = null;
            if ("GET".equals(method)){
                 response = HttpRequest.get(host + path)
                        .header(Header.AUTHORIZATION, "APPCODE " + appcode)
                        .form(querys)
                        .timeout(20000)
                        .execute();
            }else {
                response = HttpRequest.post(host + path)
                        .header(Header.AUTHORIZATION, "APPCODE " + appcode)
                        .form(querys)
                        .timeout(20000)
                        .execute();
            }

            if (response == null){
                throw new BootException("验证设置信息有误");
            }

            //获取response的body
            String requestBody = response.body();
            log.info("二要素请求返回====》{}",requestBody);
            JSONObject jsonObject = JSONObject.parseObject(requestBody);
            map.put("ret",jsonObject.get("ret"));
            map.put("msg",jsonObject.get("msg"));
            map.put("log_id",jsonObject.get("log_id"));
            if (ObjectUtil.isEmpty(jsonObject.get ("data"))){
                map.put("data", null);
            }else {
                JSONObject data = (JSONObject)jsonObject.get ("data");
                map.put ("data", data);
                map.put("code", data.get ("code"));
                map.put("desc", data.get ("desc"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 银行卡三要素校验
     * @param elementsOfBankVO 银行卡三要素 银行卡号、身份证、姓名
     * @return
     * 当 http响应状态码为200 时，以code参数返回值来做业务判断:
     * 返回值为 200 : 查询成功, 一致
     * 返回值不为200则失败
     * msg为返回说明
     */
    /* @Override
    public AlyThreeElementResultVO alyThreeElements(ElementsOfBankVO elementsOfBankVO) {
        log.info("===========三要素校验入参ElementsOfBankVO==========>{}", JSONObject.toJSONString(elementsOfBankVO));
        String host = config.getThree().getHost();
        String path = config.getThree().getPath();
        String method = config.getThree().getMethod();
        String appcode = config.getThree().getAppcode();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("bankcard", elementsOfBankVO.getCardNumber());
        bodys.put("idcard", elementsOfBankVO.getIdNumber());
        bodys.put("name", elementsOfBankVO.getName());
        AlyThreeElementResultVO alyThreeElementResultVO = new AlyThreeElementResultVO();
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            log.info("=============alyThreeElements响应体内容============>{}",JSONObject.toJSONString(response.getEntity()));
            //获取response的body
            alyThreeElementResultVO = JSON.parseObject(EntityUtils.toString(response.getEntity()), AlyThreeElementResultVO.class);
            if(alyThreeElementResultVO.getCode()== ResultCodeEnum.RESULT_SUCCESS.getCode()
                    && alyThreeElementResultVO.getData().getResult()!=ResultCodeEnum.RESULT_CODE.getCode()){
                alyThreeElementResultVO.setCode(ResultCodeEnum.RESULT_ERROR.getCode());
                alyThreeElementResultVO.setMsg(alyThreeElementResultVO.getData().getDesc());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return alyThreeElementResultVO;
    }*/

    /**
     * 银行卡四要素校验
     * @param elementsOfBankVO 银行卡四要素
     * @return
     * 当 http响应状态码为200 时，以state参数返回值来做业务判断:
     * 返回值为 1 : 查询成功, 一致
     * 返回值为 2 : 查询成功, 不一致
     * 返回值为 3：查询成功，核验结果异常
     *
     * {
     *   "request_id": "TID8bf47ab6eda64476973cc5f5b6ebf57e",
     *   "status": "OK",
     *   "state": 1,   //核验结果： 1：一致。2：不一致。 3：核验结果异常（可联系客服查询原因）
     *   "result_code": 8301,
     *   "result_message": "认证信息匹配"
     * }
     */
    /*@Override
    public ElementsOfBankResultVO alyFourElements(ElementsOfBankVO elementsOfBankVO){
        log.info("===========四要素校验入参ElementsOfBankVO==========>{}", JSONObject.toJSONString(elementsOfBankVO));
        String host = config.getFour().getHost();
        String path = config.getFour().getPath();
        String method = config.getFour().getMethod();
        String appcode = config.getFour().getAppcode();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("card_number", elementsOfBankVO.getCardNumber());
        bodys.put("id_number", elementsOfBankVO.getIdNumber());
        bodys.put("name", elementsOfBankVO.getName());
        bodys.put("phone_number",elementsOfBankVO.getPhoneNumber());
        ElementsOfBankResultVO elementsOfBankResultVO = new ElementsOfBankResultVO();
        try {
            *//**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             *//*
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            log.info("=============响应体内容============>{}",JSONObject.toJSONString(response.getEntity()));
            //获取response的body
            elementsOfBankResultVO = JSON.parseObject(JSON.parse(EntityUtils.toString(response.getEntity())).toString(), ElementsOfBankResultVO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return elementsOfBankResultVO;
    }*/

}
